<?php

class Tasks extends MY_Controller 
{
	private $user_id = 0;

	function Tasks()
	{
		parent::MY_Controller();
		
		header('Expires: Thu, 01-Jan-70 00:00:01 GMT');
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header('Pragma: no-cache');

		$this->user_id = (int)$this->session->userdata('user_id');
		if(!$this->user_id) redirect( site_url('/'), 'location');

		$this->data['header_data']['css'][] = '/css/cupertino-1.8.7/jquery-ui-1.8.7.custom.css';

		$this->data['header_data']['js'][] = '/js/jquery/jquery-1.4.3.min.js';
		$this->data['header_data']['js'][] = '/js/jquery/jquery-ui-1.8.7.custom.min.js';
		$this->data['header_data']['js'][] = '/js/tasks.js';
		$this->data['header_data']['js'][] = site_url('tasks/js_lang');

		$this->lang->load('tasks');
		$this->load->helper('tasks');

		# default title in case controller does not specify particular title
		$this->data['header_data']['page_title'] = 'turbotask.me - ' . lang('tasks');
	}

	
	
	function index($tag_id = 0)
	{
		//echo $this->config->item('sess_expiration');
		
		$this->load->model('Tasks_model', 'tasks');
		
		$tasks = $this->tasks->getTasks($this->user_id, $tag_id);
		
		# if no tasks are found for the tag in the URL, redirect to all tasks
		if($tag_id > 0 && count($tasks) === 0)
		{
			redirect( site_url('tasks'), 'location' );
			die;
		}
		
		# current time according to user's timezone settings
		$now = gmt_to_local( local_to_gmt(time()), $this->session->userdata('tz'), date('I', time()) );
		$midnight = strtotime("midnight", $now);
		$yesterday = strtotime("midnight -1 day", $now);
		$week = strtotime("midnight -7 day", $now);
		$two_weeks = strtotime("midnight -14 day", $now);
		$month = strtotime("midnight -1 month", $now);
			
		# group the tasks in different array branches depending on their create date DAY
		$grouped_tasks = array();
		foreach($tasks as $task)
		{
			$dt = gmt_to_local($task->date_created, $this->session->userdata('tz'), date('I', $now));
			
			# today
			if( $dt > $midnight )
			{
				$grouped_tasks['today'][] = $task;
			}
			# yesterday
			elseif( $dt > $yesterday )
			{
				$grouped_tasks['yesterday'][] = $task;
			}
			# before yesterday but less than a week
			elseif( $dt > $week )
			{
				$grouped_tasks['before_yesterday'][] = $task;
			}
			# before a week but less than two weeks
			elseif( $dt > $two_weeks )
			{
				$grouped_tasks['before_week'][] = $task;
			}
			# before two weeks but less than a month
			elseif( $dt > $month )
			{
				$grouped_tasks['before_two_weeks'][] = $task;
			}
			# before a month
			else
			{
				$grouped_tasks['before_month'][] = $task;
			}
		}
		
		# pass in JSON object to the view that will later be used by javascript
		$js_cfg['session_expire'] = $this->config->item('sess_expiration'); # the session lenght (expiration period)
		$viewdata['js_cfg'] = htmlspecialchars(json_encode($js_cfg));
		
		$viewdata['current_tag_id'] = (int)$tag_id;
		$viewdata['total_tasks'] = count($tasks);
		$viewdata['tasks'] = $grouped_tasks;
		$viewdata['tags'] = $this->tasks->getTags($this->user_id);
		
		# convert special chars here, because later in the view there can be problems if a tag is == <example
		for($i=0; $i<count($viewdata['tags']); $i++)
			$viewdata['tags'][$i]->name = htmlspecialchars($viewdata['tags'][$i]->name);

		$viewdata['str_tags'] = $this->_jsonTags($viewdata['tags']);		
		if((int)$tag_id > 0) $viewdata['tag_selected'] = $tag_id;
		
		$this->data['content'] = $this->load->view('tasks/tasks-new', $viewdata, true);
		
		$this->load->view('global/master-view', $this->data);
	}
	
	
	public function getOlderTasks()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}
		
		if(IS_AJAX)
		{
			$start = MAX_TASKS_VISIBLE_ON_START + 
					(int)$this->input->post('new_tasks_added') +
					(OLD_TASKS_NUM_TO_RETRIEVE * (int)$this->input->post('old_pages_loaded'));
					
			$limit = OLD_TASKS_NUM_TO_RETRIEVE;
			
			$this->load->model('Tasks_model', 'tasks');
			$tasks = $this->tasks->getTasks($this->user_id, (int)$this->input->post('current_tag_id'), $start, $limit);
			
			$result = new stdClass();
			$result->status = 'OK';
			$result->html = '';
			
			if(count($tasks) > 0)
			{				
				foreach($tasks as $task)
				{
					$result->html .= $this->load->view('tasks/one-task', array('task' => $task), true);
				}
				//log_message('debug', $result->html);
				$result->html = str_replace("\t", "", $result->html);
				//$result->html = preg_replace("/(\t|\n|\r)+/", "", $result->html);
				//log_message('debug', $result->html);
			}
			else
			{
				$result->message = lang('no_more_tasks');
			}
			
			@ob_end_clean();
			echo json_encode($result);
			die;
		}
	}
	
	
	function add()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}
		
		if($this->input->post('action') == 'addtask')
		{
			$task_content = trim($this->input->post('taskcontent'));
			$task_content = $this->input->xss_clean($task_content);
			$tag_id = (int)$this->input->post('tag_id');

			# if request for add is ajax request, return different response
			if(IS_AJAX)
			{
				$this->load->model('Tasks_model', 'tasks');
				$newtask_id = $this->tasks->insert($this->user_id, $task_content, $tag_id);
				if($newtask_id)
				{
					$task = new stdClass();
					$task->task_id = $newtask_id;
					$task->content = $task_content;					
					$task->date_created = local_to_gmt(time());
					$viewdata['task'] = $task;

					$result['status'] = 'OK';
					$result['task'] = $this->load->view('tasks/one-task', $viewdata, true);
					$result['task'] = str_replace("\t", "", $result['task']);
					
					/*
					# return status and task content
					$result['status'] = 'OK';
					$result['taskid'] = $newtask_id;
					$result['taskdate'] = date('d-M H:i', time());
					$result['taskcontent'] = htmlspecialchars($task_content);
					*/
					@ob_end_clean();
					header('HTTP/1.1 200 OK');
					header('Content-Type: application/json');
					header("Cache-Control: no-cache, must-revalidate");
					header("Expires: 0");
					echo json_encode($result);
				}
				else
				{
					@ob_end_clean();
					$result['status'] = 'ERROR';
					echo json_encode($result);
				}
				die;
			}
			else
			{
				if(empty($task_content))
				{
					$viewdata['message'] = lang('err_empty_task');
					$this->data['content'] = $this->load->view('tasks/tasks-new', $viewdata, true);
					$this->load->view('global/master-view', $this->data);
					return;
				}
				
				# save the task
				$this->load->model('Tasks_model', 'tasks');
				if($this->tasks->insert($this->user_id, $task_content))
				{
					redirect( site_url('tasks'), 'location');
				}
				else
				{
					$viewdata['message'] = lang('err_insert_newtask');
					$this->data['content'] = $this->load->view('tasks/tasks-new', $viewdata, true);
					$this->load->view('global/master-view', $this->data);
					return;					
				}
			}			
		}
	}
		
	
	/*
	 *  Save the state of a task
	 */
	public function state()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}
		
		if(IS_AJAX)
		{
			$task_id = (int) $this->input->post('task_id');
			$state = (int) $this->input->post('state');
			
			$this->load->model('Tasks_model', 'tasks');
			if( $this->tasks->setState($this->user_id, $task_id, $state) )
			{
				@ob_end_clean();
				echo 'ok';
				exit;
			}
			else
			{
				@ob_end_clean();
				echo 'error';
				exit;				
			}
		}
	}
	
	
	public function save()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}
		
		if(IS_AJAX && $this->input->post('action') == 'savetask')
		{
			$task = new stdClass();
			$task->id = (int)$this->input->post('task_id');
			$task->content = $this->input->xss_clean( $this->input->post('taskcontent') );
			$task->duedate = strtotime( $this->input->post('duedate') );
			//$task->priority = (int)$this->input->post('priority');
			$task->tags = NULL;

			$tags = $this->input->xss_clean( $this->input->post('tasktags') );
			$tags = trim($tags);
			
			$old_tags = $this->input->xss_clean( $this->input->post('oldtags') );
			$old_tags = trim($old_tags);

			# strip white spaces			
			$tags = str_replace(' ', '', $tags); 
			
			# remove commas in front and after tags
			$tags = trim($tags, ',');
			
			# if there are some tags entered, or old tags have been modified and are different from the 
			# currently submitted tags
			log_message('debug', 'tags: ' . $tags);
			log_message('debug', 'old tags: ' . $old_tags);
			
			if($tags !== $old_tags)
			{
				if(empty($tags))
					$task->tags = '';
				else
				{
					$task->tags = explode(',', $tags); # make array with tag names elements
					for($i=0; $i < count($task->tags); $i++){
						$task->tags[$i] = substr($task->tags[$i], 0, MAX_TAG_LENGTH);
					}
				}
			}

			log_message('debug', var_export($task, true));			
			$this->load->model('Tasks_model', 'tasks');

			# save the tags separately from other data
			$this->tasks->saveTags($this->user_id, $task->id, $task->tags);

			# save main task attributes
			$result = $this->tasks->save($this->user_id, $task);
			if($result)
			{
				@ob_end_clean();
				# return status and task content
				$response = array();
				$response['status'] = 'OK';
				$response['content'] = htmlspecialchars($task->content);
				$response['tags'] = is_array($tags) ? implode(',', $tags) : $tags;
				$response['tags'] = htmlspecialchars($response['tags']);
				log_message('debug', 'json response:' . var_export($response, 1));
				echo json_encode($response);
			}
			else
			{
				@ob_end_clean();
				$response = array();
				$response['status'] = 'ERROR';
				echo json_encode($response);
			}
			exit;
		}
	}
	
	
	public function delete()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}

		if(IS_AJAX)
		{
			$task_id = (int)$this->input->post('task_id');
			$this->load->model('Tasks_model', 'tasks');
			if( $this->tasks->delete($this->user_id, $task_id) )
			{
				@ob_end_clean();
				echo 'ok';
				exit;
			}
			else
			{
				@ob_end_clean();
				echo 'error';
				exit;				
			}
		}
	}
	
	
	public function priority()
	{
		# if user session has expired or he does not have a session at all
		if(!$this->user_id)
		{
			log_message('debug', '[' . __METHOD__ . '] priority: no user id');
			header('HTTP/1.1 401 Unauthorized');
			echo 'Invalid session.';
			exit;
		}

		if(IS_AJAX)
		{
			$task_id = (int)$this->input->post('task_id');
			$priority = (int)$this->input->post('priority');
			$this->load->model('Tasks_model', 'tasks');
			if( $this->tasks->priority($this->user_id, $task_id, $priority) )
			{
				log_message('debug', '[' . __METHOD__ . '] priority: OK');
				@ob_end_clean();
				echo 'ok';
				exit;
			}
			else
			{
				log_message('debug', '[' . __METHOD__ . '] priority: ERROR');
				@ob_end_clean();
				echo 'error';
				exit;				
			}
		}
	}

	# this function makes localization of javascript texts;
	# this is called as external javascript in which a javascript ARRAY is created
	# with all the javascript texts as elements of that array
	public function js_lang()
	{	
		$js_lang['empty_task'] = lang('javascript.empty_task');
		$js_lang['add_task_err'] = lang('javascript.add_task_err');
		$js_lang['error'] = lang('javascript.error');
		$js_lang['save_task_err'] = lang('javascript.save_task_err');
		$js_lang['del_task_err'] = lang('javascript.del_task_err');
		
		@ob_end_clean();
		echo 'var L10N = ' . json_encode($js_lang);
		die;
	}

	
	private function _jsonTags($tags)
	{
		if( ! is_array($tags)) return FALSE;
		
		$tagsArray = array();
		foreach($tags as $tag)
		{
			$tagsArray[] = $tag->name;
		}		
		return json_encode($tagsArray);
	}	

}